import { Form, Input, Table, Tabs } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';

const MultiTableSetSelectInfo = ({ uploadInfo, setUploadInfo }) => {
  const [activeTab, setActiveTab] = useState('');
  const [hasSelectInfo, setHasSelectInfo] = useState(false);
  const [backendData, setBackendData] = useState([]);

  //获取所有选项数据
  const getSelectInfo = () => {
    fetch(API_URL + '/importTable/getTableElements', {
      method: 'post',
      body: JSON.stringify(uploadInfo),
      headers: { 'Content-Type': 'application/json' },
    })
      .then((res) => res.json())
      .then(function (data) {
        console.log(data);
        if (data) {
          //将返回的元素设置进uploadinfo
          setUploadInfo({ ...uploadInfo, tablesElements: data });
          let tableSelectData = [];
          let selectData = {};
          data.forEach((e) => {
            let { tableName, canvasName, elements } = e;
            //校验是否有查询组件
            let selectElements = elements.filter((e) => e.dataType === 'SELECT');

            if (selectElements && selectElements.length == 0) {
              return;
            } else {
              setHasSelectInfo(true);
              //存在查询组件，设置值
              let selectData = {
                title: tableName,
                data: selectElements.map((e) => {
                  let { title, colNum, rowNum, tableNum } = e;
                  return {
                    key: rowNum + '_' + colNum,
                    selectName: title,
                    options: '请填写内容',
                    canvasName,
                    colNum,
                    rowNum,
                    tableNum,
                  };
                }),
              };
              tableSelectData.push(selectData);
            }
          });
          if (selectData) {
            setBackendData(tableSelectData);
            setActiveTab(tableSelectData[0].title);
          }
        }
      });
  };

  //初始化数据
  useEffect(() => {
    getSelectInfo();
  }, []);

  const handleTabChange = (key) => {
    setActiveTab(key);
  };

  /**
   * 可编辑单元格
   */
  //可编辑表格组件
  const EditableContext = React.createContext(null);
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus({ cursor: 'all' });
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `请填写内容`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} placeholder="请填写内容" />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };

  //编辑后事件，修改选项名称
  const handleSave = (row) => {
    setBackendData((prevData) => {
      let newBackendData = prevData.map((e) => {
        if (e.title === activeTab) {
          let newData = e.data.map((item) => (item.key === row.key ? { ...item, ...row } : item));
          return { ...e, data: newData };
        }
        return e;
      });
      return newBackendData;
    });
    // 更新 uploadInfo 中的 tablesElements
    setUploadInfo((prevUploadInfo) => {
      let newTablesElements = prevUploadInfo.tablesElements.map((tableElement) => {
        if (tableElement.tableName === activeTab) {
          let newElements = tableElement.elements.map((element) => {
            if (element.rowNum === row.rowNum && element.colNum === row.colNum) {
              return { ...element, title: row.selectName, options: row.options };
            }
            return element;
          });
          return { ...tableElement, elements: newElements };
        }
        return tableElement;
      });
      return { ...prevUploadInfo, tablesElements: newTablesElements };
    });
  };
  const defaultColumns = [
    {
      title: '选项组件名称',
      dataIndex: 'selectName',
      width: '40%',
      key: 'selectName',
    },
    {
      title: '选项（以“，”分割）',
      dataIndex: 'options',
      key: 'options',
      width: '60%',
      editable: true,
    },
  ];

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const items = getItems(backendData);
  function getItems(backendData) {
    backendData.map(({ title, data }) => ({
      key: title,
      label: title,
      children: (
        <Table
          bordered
          rowClassName={() => 'editable-row'}
          components={components}
          dataSource={data}
          columns={columns}
          pagination={false}
        />
      ),
    }));
    return;
  }

  return (
    <div>
      {hasSelectInfo ? (
        <Tabs defaultActiveKey={activeTab} items={items} onChange={handleTabChange} />
      ) : (
        <div>无选项组件，请继续下一步</div>
      )}
    </div>
  );
};

export default MultiTableSetSelectInfo;
